﻿using DataAccess;
using DataAccess.Api;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using DataAccess.Solr;
using DataAccess.ViewModel.Agent;
using Gma.QrCodeNet.Encoding;
using Gma.QrCodeNet.Encoding.Windows.Render;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace Agent.Controllers
{
    public class AgentCenterController : BaseController
    {
        //
        //代理中心
        public ActionResult Index()
        {

            //用户基本信息
            ViewBag.Img = string.IsNullOrEmpty(AgencyUsers.head_img) ? "http://0d077ef9e74d8.cdn.sohucs.com/qoY5WYF_png" : AgencyUsers.head_img;
            ViewBag.Username = AgencyUsers.nickname;

            ViewBag.permission = string.IsNullOrEmpty(AgencyUsers.permission) ? "" : AgencyUsers.permission;

            //用户收入信息
            OrdersDAL dal = new OrdersDAL();
            var model = dal.GetAgentTodayStatistics(UserSession.user_name, AgencyUsers.promoter_id);
            decimal rate = (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);
            model.income = model.income * rate;
            model.settle = model.settle * rate;



            return View(model);
        }

        /// <summary>
        /// 近期推广业绩
        /// </summary>
        /// <returns></returns>
        public ActionResult TGYJ()
        {
            ProductEffectDAL dal = new ProductEffectDAL();


            #region 历史数据
            var list = dal.GetRecentInfo(AgencyUsers.promoter_id.ToString(), AgencyUsers.username);


            if (list == null)
            {
                list = new List<DataAccess.DTO.ProductEffect_RecentDTO>();
                list.Add(new ProductEffect_RecentDTO()
                {
                    //type = "yesterday_income"
                    type = "昨日成交汇总"
                });
                list.Add(new ProductEffect_RecentDTO()
                {
                    //type = "current_month_income"
                    type = "本月成交汇总"
                });
                list.Add(new ProductEffect_RecentDTO()
                {
                    //type = "last_month_income"
                    type = "上月成交汇总"
                });
            }
            else
            {
                decimal rate = (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);
                list.ForEach(l =>
                {
                    l.type = l.type == "yesterday_income" ? "昨日成交汇总" : l.type == "current_month_income" ? "本月成交汇总" : "上月成交汇总";
                    l.income = l.income * rate;
                    l.estimate = l.estimate * rate;

                });
            }
            #endregion
            //今日佣金
            var model = new OrdersDAL().GetAgentTodayStatistics(UserSession.user_name, AgencyUsers.promoter_id);
            if (model != null)
            {


                list.Insert(0, new ProductEffect_RecentDTO()
                {
                    type = "今日成交汇总",
                    paynum = model.ordernum,
                    estimate = model.income * (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00)
                });
            }
            else
            {
                list.Insert(0, new ProductEffect_RecentDTO()
                {
                    type = "今日成交汇总"
                });
            }
            return View(list);
        }

        /// <summary>
        /// 淘宝订单查看(不用了)
        /// </summary>
        /// <returns></returns>
        public ActionResult Order()
        {
            return View();
        }
        [HttpPost]
        public JsonResult OrderPost(int limit, int type = 0, string orderId = "")
        {
            OrdersDAL dal = new OrdersDAL();

            string where = " au_name=@au_name ";
            switch (type)
            {
                case 1:
                    where += " and OrderStateDes='订单付款' ";
                    break;
                case 2:
                    where += " and OrderStateDes='订单失效' ";

                    break;
                case 3:
                    where += " and OrderStateDes='订单结算' ";
                    break;


            }

            if (!string.IsNullOrEmpty(orderId))
            {
                where += " and OrderID=@OrderID";
            }

            //switch (timetype)
            //{
            //    case 1:
            //        where += " and createdate ='" + DateTime.Now.ToString("yyyy-MM-dd") + "' ";

            //        break;
            //    case 2:
            //        where += " and createdate ='" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + "' ";

            //        break;
            //    case 3:
            //        where += " and createdate >'" + DateTime.Now.ToString("yyyy-MM-01") + "' ";

            //        break;
            //}
            string orderbys = "";
            int count = 0;

            List<Orders> tbkItems = new DataAccess.DAL.OrdersDAL().ListPage(AgencyUsers.promoter_id, where, orderbys, 10, limit, out count, new { OrderID = orderId, au_name = UserSession.user_name });

            decimal rate = (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);

            //var newList = from l in tbkItems
            //            select new {  };

            tbkItems.ForEach(l => { l.EffectPrediction = Math.Round((l.EffectPrediction * (double)rate), 2); });

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = tbkItems;
            return Json(result);


        }


        /// <summary>
        /// 个人推广详情
        /// </summary>
        /// <returns></returns>
        public ActionResult MyEffect(int pi = 1)
        {
            //int ps=20;
            //int count=0;
            //ProductEffectDAL dal = new ProductEffectDAL();
            //string where="";
            //var list = dal.ListPage(where, " createdate desc ", ps, pi, out count);
            // List<EffectDetailsVM> newList = new List<EffectDetailsVM>();


            return View();
        }



        /// <summary>
        /// 获取推广详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetEffect(int dateType = 1, int pi = 1)
        {
            Result res = new Result() { State = false, Message = "请求失败" };

            //int pi = 1;
            int ps = 20;
            int count = 0;
            ProductEffectDAL dal = new ProductEffectDAL();
            string where = " username=@username ";
            if (dateType > 0)
            {
                switch (dateType)
                {
                    case 1:
                        where += string.Format(" and CreateDate>='{0}'", DateTime.Now.ToString("yyyy-MM-01"));
                        break;
                    case 2:
                        where += string.Format(" and CreateDate>='{0}' and CreateDate<'{1}'", DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01"), DateTime.Now.ToString("yyyy-MM-01"));

                        break;
                    case 3:
                        break;


                    default:
                        break;
                }
            }
            var list = dal.ListPage(AgencyUsers.promoter_id, where, " createdate desc ", ps, pi, out count, new { username = UserSession.user_name });

            decimal rate = (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);


            var newList = from l in list
                          select new EffectDetailsVM() { DateTime = l.CreateDate.ToString("MM-dd"), ClickNum = l.ClickNum, PayNum = l.PayNum.ToString(), Type = l.PromotionBit.Contains("wx") ? "微信推广" : "网站推广", Estimate = (l.Estimate * rate).ToString("C"), Income = (l.Income * rate).ToString("C") };
            res.State = true;
            res.Message = "请求成功";
            res.Datas = newList;


            return Json(res);
        }

        /// <summary>
        /// 英雄榜
        /// </summary>
        /// <returns></returns>
        public ActionResult Hero()
        {
            return View();
        }
        /// <summary>
        /// 搜索商品
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            return View();
        }
        /// <summary>
        /// 超级搜索
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        public ActionResult SearchKeyWord(string keyword)
        {
            ViewBag.keyword = keyword;
            return View();
        }
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        private int GetCreatetime()
        {

            DateTime DateStart = new DateTime(1970, 1, 1, 8, 0, 0);

            return Convert.ToInt32((DateTime.Now - DateStart).TotalSeconds);

        }
        /// <summary>
        /// 超级搜索查询接口
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public ActionResult GetSearchProduct(string keyword, int limit)
        {
            string content = string.Empty;
            string url = string.Format("http://pub.alimama.com/items/search.json?q={0}&_t={1}&toPage={6}&dpyhq=1&auctionTag=&perPageSize=40&shopTag=yxjh%2Cdpyhq&t={2}&_tb_token_=test&pvid=10_{3}_{5}_{4}", System.Web.HttpUtility.UrlEncode(keyword), GetCreatetime(), GetCreatetime(), XYD.Common.Request.GetIP(), GetCreatetime(), rd.Next(0, 9999), limit);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Host = "pub.alimama.com";
            req.Accept = "application/json, text/javascript, */*; q=0.01";
            req.Referer = string.Format("http://pub.alimama.com/promo/search/index.htm?q={0}&_t={1}&toPage={2}&dpyhq=1", System.Web.HttpUtility.UrlEncode(keyword), GetCreatetime(),limit);  
            req.Method = "GET";
            try
            {
                using (WebResponse wr = req.GetResponse())
                {
                    StreamReader weatherStreamReader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
                    content = weatherStreamReader.ReadToEnd();
                    TbProduct pro = ServiceStack.Text.JsonSerializer.DeserializeFromString<TbProduct>(content);
                    string Str = "";
                    foreach (var item in pro.data.pageList)
                    {
                        Str += "{\"title\":\"" + item.title + "\",\"istmall\":" + item.userType + ",\"num_iid\":" + item.auctionId + ",\"org_price\":" + item.zkPrice + ",\"price\":" + (item.zkPrice - item.couponAmount) + ",\"coupons_price\":" + item.couponAmount + ",\"goods_sale\":" + item.biz30day + ",\"url\":\"" + item.auctionUrl + "\",\"pic_url\":\"" + item.pictUrl + "\",\"coupons_end\":\"" + item.couponEffectiveEndTime + "\",\"t1\":\"" + (string.IsNullOrEmpty(item.eventRate) ? "0" : item.eventRate) + "\",\"t2\":\"" + (item.includeDxjh == null ? 0 : item.includeDxjh) + "\",\"t3\":\"" + item.tkRate + "\",\"t4\":\"" + item.tkSpecialCampaignIdRateMap + "\",\"couponLeftCount\":\"" + item.couponLeftCount + "\"},";
                    }
                    if (Str != "")
                    {
                        Str = Str.Substring(0, Str.Length - 1);
                    }
                    Str = "{\"DataList\":[" + Str + "],\"status\":1,\"lm\":1}";
                    return Content(Str);
                }
               
                
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        //转链接
        public ActionResult GetSearchLink(string link,string convertType)
        {
            string text = "";
            var DataInfo=new object();

            string content = string.Empty;
            string url = string.Format("http://pub.alimama.com/items/search.json?q={0}&auctionTag=&perPageSize=40", System.Web.HttpUtility.UrlEncode(link));
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            req.Host = "pub.alimama.com";
            req.Accept = "application/json, text/javascript, */*; q=0.01";
            req.Referer = string.Format("http://pub.alimama.com/promo/search/index.htm?q={0}&", System.Web.HttpUtility.UrlEncode(link));
            req.Method = "GET";
            try
            {
                using (WebResponse wr = req.GetResponse())
                {
                    StreamReader weatherStreamReader = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
                    content = weatherStreamReader.ReadToEnd();
                    TbProduct pro = ServiceStack.Text.JsonSerializer.DeserializeFromString<TbProduct>(content);
                    string Str = "";

                    if (pro.data.pageList == null || pro.data.pageList.Count == 0)
                    {
                        return Json(new { DataInfo = "", status =2 });
                        //没有找到优惠券商品
                    }

                    foreach (var item in pro.data.pageList)
                    {
                        

                        //价格  item.zkPrice
                        string zkPrice = item.zkPrice.ToString("F2");
                        //优惠  item.couponAmount
                        string couponAmount = item.couponAmount.ToString("F2");
                        //券后价格 item.zkPrice - item.couponAmount
                        string couponPrice = (item.zkPrice - item.couponAmount).ToString("F2");
                        
                        //最终佣金
                        double rate_all = 0;
                        //最终佣金比率
                        double rate = 0;
                        //淘口令
                        string tkl = "";

                        //短链接
                        string shortUrl = "";

                        //商品id item.auctionId
                        string auctionId = item.auctionId.ToString();
                        //t2  (item.includeDxjh == null ? 0 : item.includeDxjh) 

                        //t1 (string.IsNullOrEmpty(item.eventRate) ? "0" : item.eventRate) 

                        //t3 item.tkRate

                        //t4 item.tkSpecialCampaignIdRateMap

                        //////////////////////////////
                        string eventRate = (string.IsNullOrEmpty(item.eventRate) ? "0" : item.eventRate);
                        string tkRate = item.tkRate;
                        int includeDxjh = (item.includeDxjh == null ? 0 : item.includeDxjh);
                        string tkSpecialCampaignIdRateMap = item.tkSpecialCampaignIdRateMap==null ? "" : item.tkSpecialCampaignIdRateMap.ToString();
                        string str = new RobotApiHelper().SuperSearch(AgencyUsers.alimamaid, item.auctionId.ToString(), convertType == "1" ? AgencyUsers.wechat_adzoneid : convertType == "2" ? AgencyUsers.qq_adzoneid : AgencyUsers.site_adzoneid, includeDxjh, eventRate, tkRate, tkSpecialCampaignIdRateMap, convertType == "1" ? "wx" : convertType=="2"?"qq":"wz");
                        Kouling model = ServiceStack.Text.JsonSerializer.DeserializeFromString<Kouling>(str);
                      
                        if (model != null)
                        {
                            //产品优惠后的价格*百分只比
                            //  （100-15）/100.00*0.40
                            double Rate_price = double.Parse(couponPrice) * (model.data.tkRate / 100.00);

                            //最终佣金
                            rate_all = (Rate_price - (Rate_price * (SysConfig.rate_all / 100.00))) * (SysConfig.rate / 100.00);
                            //最终佣金比率
                            rate = (rate_all / double.Parse(couponPrice)) * 100;

                            tkl = model.data.activityIdtkPassword;
                            shortUrl = model.data.activityIdshortUrl;
                            //return Content("{\"ratePrice\":\"" + rate_all.ToString("F2") + "\",\"rate\":\"" + rate.ToString("F2") + "\",\"Url\":\"" + model.data.shortUrl + "\",\"kl\":\"" + model.data.tkPassword + "\",\"hz\":\"" + (SysConfig.domain + "/shop/" + UserSession.user_name + ".html") + "\"}");
                        }

                       

                        //////////////////////////////////
                       
                        if (item.couponAmount > 0)//有优惠券
                        {
                            text = string.Format(@" {0}
 ┄┄┄┄┄┄
 原　价：【{1}】元
 券后【{2}元】包邮秒杀
 ┄┄┄┄┄┄
 复制这条消息, 打开【手机淘宝】即可购买{3}つ{4} 
（优惠汇总）点此进入要什么就搜索什么：http://{5}", item.title, item.zkPrice, (item.zkPrice - item.couponAmount).ToString("F2"),tkl,shortUrl, (SysConfig.domain + "/shop/" + UserSession.user_name + ".html"));
                        }
                        else
                        {
                            tkl = model.data.taoToken;
                            shortUrl = model.data.shortLinkUrl;

                            text = string.Format(@" {0}
 ┄┄┄┄┄┄
 价　格：【{1}】元
 ┄┄┄┄┄┄
 复制这条消息, 打开【手机淘宝】即可购买{2}つ{3} 
（优惠汇总）点此进入要什么就搜索什么：http://{4}", item.title, item.zkPrice, tkl, shortUrl, (SysConfig.domain + "/shop/" + UserSession.user_name + ".html"));
                        
                        }



                        //Str += "{\"title\":\"" + item.title + "\",\"istmall\":" + item.userType + ",\"num_iid\":" + item.auctionId + ",\"org_price\":" + item.zkPrice + ",\"price\":" + (item.zkPrice - item.couponAmount) + ",\"coupons_price\":" + item.couponAmount + ",\"goods_sale\":" + item.biz30day + ",\"url\":\"" + item.auctionUrl + "\",\"pic_url\":\"" + item.pictUrl + "\",\"coupons_end\":\"" + item.couponEffectiveEndTime + "\",\"t1\":\"" + (string.IsNullOrEmpty(item.eventRate) ? "0" : item.eventRate) + "\",\"t2\":\"" + (item.includeDxjh == null ? 0 : item.includeDxjh) + "\",\"t3\":\"" + item.tkRate + "\",\"t4\":\"" + item.tkSpecialCampaignIdRateMap + "\",\"couponLeftCount\":\"" + item.couponLeftCount + "\",text:\"" + text + "\"}";

                        DataInfo = new { title = item.title, istmall = item.userType, num_iid = item.auctionId, org_price = item.zkPrice, price = (item.zkPrice - item.couponAmount), coupons_price = item.couponAmount, goods_sale = item.biz30day, url = item.auctionUrl, pic_url = item.pictUrl, coupons_end = item.couponEffectiveEndTime, couponLeftCount = item.couponLeftCount, text = text, concession = rate_all.ToString("F2"), concession_rate = rate.ToString("F2") };

                        break;
                    }


                    if (Str != "")
                    {
                       // Str = Str.Substring(0, Str.Length - 1);
                    }
                    else
                    {
                       

                    }
                   // Str = "{\"DataInfo\":" + Str + ",\"status\":1}";
                    return Json(new { DataInfo = DataInfo, status = 1 });
                }


            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /// <summary>
        /// 超级搜索转链
        /// </summary>
        /// <param name="id"></param>
        /// <param name="includeDxjh"></param>
        /// <param name="eventRate"></param>
        /// <param name="tkRate"></param>
        /// <param name="tkSpecialCampaignIdRateMap"></param>
        /// <returns></returns>
        public ActionResult SearchKl(string id, int t2, string t1, string t3, string t4, string Price)
        {
            if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(t1) && !string.IsNullOrEmpty(t3)  && !string.IsNullOrEmpty(Price))
            {
                string eventRate = t1;
                string tkRate = t3;
                int includeDxjh = t2;
                string tkSpecialCampaignIdRateMap = t4;
                string str = new RobotApiHelper().SuperSearch(AgencyUsers.alimamaid, id, AgencyUsers.site_adzoneid, includeDxjh, eventRate, tkRate, tkSpecialCampaignIdRateMap);
                Kouling model = ServiceStack.Text.JsonSerializer.DeserializeFromString<Kouling>(str);
                if (model != null)
                {
                    //产品优惠后的价格*百分只比
                    //  （100-15）/100.00*0.40
                    double Rate_price = double.Parse(Price) * (model.data.tkRate / 100.00);
                     
                    double rate_all = (Rate_price - (Rate_price * (SysConfig.rate_all / 100.00))) * (SysConfig.rate / 100.00);
                    double rate = (rate_all / double.Parse(Price)) * 100;
                    return Content("{\"ratePrice\":\"" + rate_all.ToString("F2") + "\",\"rate\":\"" + rate.ToString("F2") + "\",\"Url\":\"" + model.data.activityIdshortUrl + "\",\"kl\":\"" + model.data.activityIdtkPassword + "\",\"hz\":\"" + (SysConfig.domain + "/shop/" + UserSession.user_name + ".html") + "\"}");
                }
            }
            return null;
        }
        /// <summary>
        /// 代理产品库
        /// </summary>
        /// <returns></returns>
        public ActionResult Product()
        {
            ViewBag.aid = UserSession.user_name;
            return View();
        }
        /// <summary>
        /// 获取代理产品库
        /// </summary>
        /// <returns></returns>
        public ActionResult DLProduct()
        {


            SolrDLIndexInfoBLL bll = new SolrDLIndexInfoBLL();
            int offset = XYD.Common.Request.GetFormInt("pi", 1);
            int classid = XYD.Common.Request.GetFormInt("cid", 0);

            int sort = XYD.Common.Request.GetFormInt("orderby", 0);
            string Key = XYD.Common.Request.GetFormString("Key");
            string strwhere = "(biz30day:[0 TO *])";
            if (classid != 0)//按分类查找 
            {
                strwhere += string.Format("AND(DataTypeID:{0})", classid);
            }


            if (!string.IsNullOrEmpty(Key))
            {
                strwhere += "AND(";
                strwhere += string.Format("(productname:{0})", Key);
                strwhere += ")";
                //搜索
            }

            string Order = "synchro_date desc";
            switch (sort)
            {
                case 0:
                    Order = "couponTotalCount desc";//综合
                    break;
                case 1:
                    Order = "biz30day desc";//销量
                    break;
                case 2:
                    Order = "prices asc";//价格
                    break;
                case 3:
                    Order = "couponAmount desc";//优惠率
                    break;
                case 4:
                    Order = "tkRate desc";//佣金
                    break;
                case 5:
                    Order = "synchro_date desc";//最新
                    break;
                default:
                    break;
            }
            //爆款热销
            if (XYD.Common.Request.GetFormString("gender") != "")
            {
                Order = "biz30day desc";//销量
            }

            // offset = offset >0 ? (offset - 1) * 20 + 1 : 0;

            offset = offset > 0 ? (offset - 1) * 20 + 1 : 0;


            PagingList<ProductDLIndex> plist = bll.GetProductList(strwhere, offset, 20, Order);
            if (plist.CurrentPageList != null && plist.CurrentPageList.Count > 0)
            {

                double rate = (((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);


                plist.CurrentPageList.ForEach(l =>
                {
                    l.tkRate = (float.Parse(l.tkRate) * rate).ToString("C");
                });
            }


            if (!string.IsNullOrEmpty(Key))
            {
                SearchKeyWordDAL.InsertKeyWord(1, 1, 1, Key, "", plist.Total, "", XYD.Common.Request.GetIP(), "网站搜索");
            }
            return Json(new { State = true, Message = "查询成功", total = plist.Total, rows = plist });

        }

        /// <summary>
        /// 查询商品详情
        /// </summary>
        /// <returns></returns>
        public JsonResult Goods(string id)
        {
            SolrProductDetails bll = new SolrProductDetails();
            if (!string.IsNullOrEmpty(id) && id != "0")
            {
                var model = bll.GetProductDetailsByProductInfo(id);
                if (model != null)
                {
                    double rate = (((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);
                    model.Rate = (model.Rate * rate);
                    model.tkRate = float.Parse((model.Rate / float.Parse(model.Price) * 100).ToString("F2"));
                   

                    return Json(new { State = true, Message = "查询成功", rows = model });
                }
            }

            return Json(new { State = false, Message = "查询失败" });

        }
        Random rd = new Random();
        /// <summary>
        /// 生成推广信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult Kouling(int? id, string pid)
        {
            if (id.HasValue && !string.IsNullOrEmpty(pid))
            {
                var model = new SolrProductDetails().GetProductDetailsByProductInfo(pid);
                if (model != null)
                {
                    string[] tb = SysConfig.tb_open.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                    int index = rd.Next(tb.Length);
                    if (index % 2 != 0)
                    {
                        index = index - 1;
                    }
                    ////申请计划
                    //new RobotApiHelper().FrontItemChain(AgencyUsers.promoter_id.ToString(), AgencyUsers.username, pid);
                    string kl = "";
                    //申请计划
                    var ficStr = new RobotApiHelper().FrontItemChain(SysConfig.promoter_id.ToString(), AgencyUsers.username, pid);

                    var ficModel = XYD.Common.JsonHelper.DeserializeJson<FrontItemChainDTO>(ficStr);
                    if (ficModel != null)
                    {
                        if (ficModel.state == 2)
                        {
                            kl = string.IsNullOrEmpty(ficModel.date.activityIdtkPassword) ? ficModel.date.taoToken : ficModel.date.activityIdtkPassword;
                        }
                        else
                        {
                            kl = DataAccess.TB.Tkl.CreateToken(model.pictUrl,
                      model.title, model.couponActivityId,
                        AgencyUsers.site_pid,
                       model.auctionId.ToString(), "3254152761",
                      tb[index],
                      tb[index + 1]);
                        }

                    }




                   
                    string shortUrl = "";
                    try
                    {
                        string stractivityUrl = string.Format("http://uland.taobao.com/coupon/edetail?activityId={0}&pid={1}&itemId={2}", model.couponActivityId, AgencyUsers.site_pid, model.auctionId);
                        shortUrl = DataAccess.SortUrl.CreateShortUrl(stractivityUrl);
                    }
                    catch (Exception)
                    {

                        shortUrl = "";
                    }

                    string Html = "";
                    if (id == 1)
                    {
                        Html = string.Format(@"{0}
【推荐理由】{1}
┄┄┄┄┄┄
原　价：【 {2}】元
券后价：【 {3}】元 
┄┄┄┄┄┄
复制这条消息, 打开【手机淘宝】即可购买{4}つ http://f-2.cc/{5}
（优惠汇总）点此进入要什么就搜索什么：http://{6}

", model.title, model.Introduce, model.zkPrice, model.Price, kl, shortUrl, SysConfig.domain + "/shop/" + UserSession.user_name + ".html");
                    }
                    else
                    {
                        Html = string.Format(@"{0}
【推荐理由】{1}
┄┄┄┄┄┄
原　价：【 {2}】元
券后价：【 {3}】元 
┄┄┄┄┄┄
复制这条消息, 打开【手机淘宝】即可购买{4}つ http://f-2.cc/{5}
（优惠汇总）点此进入要什么就搜索什么：http://{6}

", model.title, model.Introduce, model.zkPrice, model.Price, kl, shortUrl, SysConfig.domain + "/shop/" + UserSession.user_name + ".html");
                    }
                    return Json(new { State = true, Message = "查询成功", date = Html });
                }

            }
            return null;
        }
        

        /// <summary>
        /// 生成二维码
        /// </summary>
        /// <param name="strContent"></param>
        /// <param name="ms"></param>
        /// <returns></returns>
        public static bool GetQRCode(string strContent, MemoryStream ms)
        {
            ErrorCorrectionLevel Ecl = ErrorCorrectionLevel.M; //误差校正水平   
            string Content = strContent;//待编码内容  
            QuietZoneModules QuietZones = QuietZoneModules.Two;  //空白区域   
            int ModuleSize = 12;//大小  
            var encoder = new QrEncoder(Ecl);
            QrCode qr;
            if (encoder.TryEncode(Content, out qr))//对内容进行编码，并保存生成的矩阵  
            {
                var render = new GraphicsRenderer(new FixedModuleSize(ModuleSize, QuietZones));
                render.WriteToStream(qr.Matrix, ImageFormat.Png, ms);
            }
            else
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取二维码图片
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQRImg()
        {
            string url = System.Web.HttpContext.Current.Request.Url.Host + "/shop/" + base.AgencyUsers.username + ".html";
            using (var ms = new MemoryStream())
            {
                GetQRCode(url, ms);
                Response.ContentType = "image/Png";
                Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
                Response.End();
            }
            return null;
        }
        public ActionResult Hehuoren()
        {
            return View();
        }
        /// <summary>
        /// 获取合伙人
        /// </summary>
        /// <param name="type">1 朋友  2朋友的朋友 </param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetHehuoren(int type = 1, int limit = 1)
        {
            AgencyUsersDAL dal = new AgencyUsersDAL();

            int count = 0;
            string where = " 1=1 ";
            if (type == 1)
            {
                where += " and superior=" + UserSession.user_id;
            }
            else
            {
                where += "and onthe_superior=" + UserSession.user_id;

            }

            string sql = string.Format(" id,username,nickname,head_img,superior_commission,onthe_superior_commission,(select count(1) from [Orders_{0}]  where au_name= username  and CreateDate>'{1}' )order_number  ,(select sum(EffectPrediction) from [Orders_{0}] where au_name= username and CreateDate>'{1}'  ) income ", AgencyUsers.promoter_id, DateTime.Now.ToString("yyyy-MM-dd"));





            var list = dal.ListPage<AgencyUsersDTO>(sql, "[AgencyUsers]", where, "", "", " add_data desc ", 10, limit, out count);

            var rateAll = SysConfig.rate_all;

            var resList = from l in list
                          select new { username = l.username, nickname = l.nickname, head_img = l.head_img, order_number = l.order_number, income = (type == 1 ? ((double)l.income * ((100 - rateAll) * (l.superior_commission / 100.00) / 100.00)).ToString("C") : ((double)l.income * ((100 - rateAll) * (l.onthe_superior_commission / 100.00) / 100.00)).ToString("C")) };

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = resList;
            return Json(result);

        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult UserInfo()
        {
            var model = new AgencyUsersDAL().Get(base.UserSession.user_id);
            if (model != null)
                return View(model);
            else
                return Redirect("/u");
        }
        /// <summary>
        /// 代理信息修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult userupdate()
        {
            AgencyUsersDAL dal = new AgencyUsersDAL();
            var model = dal.Get(base.UserSession.user_id);

            if (string.IsNullOrEmpty(model.AlipayID) || string.IsNullOrEmpty(model.AliName))
            {
                model.AlipayID = XYD.Common.Request.GetFormString("AlipayID");
                model.AliName = XYD.Common.Request.GetFormString("AliName");
            }

            model.head_img = XYD.Common.Request.GetFormString("head_img");
            model.wx_name = XYD.Common.Request.GetFormString("wx_name");
            model.tel = XYD.Common.Request.GetFormString("tel");
            model.nickname = XYD.Common.Request.GetFormString("nickname");
            model.UpdateTime = DateTime.Now;
            if (dal.Update(model))
            {
                RedisHelper.Single_Remove_Itme(RedisKey.AgencyUser(AgencyUsers.promoter_id.ToString(), AgencyUsers.username));

                //

                return Json(new Result { State = true, Message = "更新成功" });
            }
            return Json(new Result { State = false, Message = "更新失败" });
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="password"></param>
        /// <param name="password1"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdatePwd(string password, string password1)
        {
            AgencyUsersDAL dal = new AgencyUsersDAL();
            var model = dal.Get(base.UserSession.user_id);
            string pw1 = XYD.Common.EncodeSecurity.EncryptString(password);
            if (pw1 != model.password)
            {
                return Json(new Result { State = false, Message = "原始密码不正确" });
            }
            model.password = XYD.Common.EncodeSecurity.EncryptString(password1);
            if (dal.Update(model))
            {
                return Json(new Result { State = true, Message = "更新成功" });
            }
            return Json(new Result { State = false, Message = "更新失败" });
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        public ActionResult PasswordEdit()
        {
            return View();
        }
        /// <summary>
        /// 成交订单
        /// </summary>
        /// <returns></returns>
        public ActionResult CJDD()
        {
            return View();
        }
      
        /// <summary>
        /// 提现和记录
        /// </summary>
        /// <returns></returns>
        public ActionResult TiXian()
        {
            return View();
        }


        /// <summary>
        /// 推广统计
        /// </summary>
        /// <returns></returns>
        public ActionResult TGTJ()
        {
            return View();
        }


        public ActionResult GetTGTJ(int dateType = 0)
        {
            Result res = new Result() { State = false, Message = "请求失败" };

            // int pi = 1;
            int ps = 7;
            int count = 0;
            ProductEffectDAL dal = new ProductEffectDAL();
            string where = " username=@username ";

            if (dateType > 0)
            {
                switch (dateType)
                {
                    case 1:
                        where += string.Format(" and CreateDate>='{0}'", DateTime.Now.ToString("yyyy-MM-01"));
                        break;
                    case 2:
                        where += string.Format(" and CreateDate>='{0}' and CreateDate<'{1}'", DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01"), DateTime.Now.ToString("yyyy-MM-01"));

                        break;
                    case 3:
                        break;


                    default:
                        break;
                }
            }

            var list = dal.ListPage(AgencyUsers.promoter_id, where, " createdate desc ", ps, 1, out count, new { username = UserSession.user_name });

            List<string> dateTimeArray = new List<string>();
            List<string> djtjArray = new List<string>();
            List<string> ddtjArray = new List<string>();
            List<string> ygtjArray = new List<string>();
            List<string> jstjArray = new List<string>();
            decimal rate = (decimal)(((100 - SysConfig.rate_all) * (AgencyUsers.commission / 100.00)) / 100.00);

            list.ForEach(l =>
            {
                dateTimeArray.Add(l.CreateDate.ToString("MM-dd"));
                djtjArray.Add(l.ClickNum.ToString());
                ddtjArray.Add(l.PayNum.ToString());
                ygtjArray.Add(string.Format("{0:N}", l.Estimate * rate));
                jstjArray.Add(string.Format("{0:N}", l.Income * rate));

            });




            res.State = true;
            res.Message = "请求成功";
            res.Datas = new { dateTime = dateTimeArray.ToArray(), djtj = djtjArray.ToArray(), ddtj = ddtjArray.ToArray(), ygtj = ygtjArray.ToArray(), jstj = jstjArray.ToArray() };
            return Json(res);
        }


        /// <summary>
        /// 合伙人推广分析
        /// </summary>
        /// <returns></returns>
        public ActionResult HhrTGFX()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GetHhrTGFX(int dateType = 1, int agentType = 1)
        {
            Result res = new Result() { State = false, Message = "请求失败" };

            //int pi = 1;
            int ps = 20;
            int count = 0;
            ProductEffectDAL dal = new ProductEffectDAL();
            string where = " where 1=1 ";
            if (dateType > 0)
            {
                switch (dateType)
                {
                    case 1:
                        where += string.Format(" and p.CreateDate>='{0}'", DateTime.Now.ToString("yyyy-MM-01"));
                        break;
                    case 2:
                        where += string.Format(" and p.CreateDate>='{0}' and p.CreateDate<'{1}'", DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01"), DateTime.Now.ToString("yyyy-MM-01"));

                        break;

                }
            }
            if (agentType == 1)
            {
                where += " and au.superior=@auid ";
            }
            if (agentType == 2)
            {
                where += " and au.onthe_superior=@auid ";
            }

            string sql = " select top 50 p.* from [ProductEffect_" + AgencyUsers.promoter_id + "] p left join  [dbo].[AgencyUsers] au on p.username=au.username  " + where;

            var list = dal.List<ProductEffect>(sql, new { auid = AgencyUsers.id });
            var newList = from l in list
                          select new { DateTime = l.CreateDate.ToString("MM-dd"), ClickNum = l.ClickNum, PayNum = l.PayNum.ToString(), Type = l.PromotionBit.Contains("wx") ? "微信推广" : "网站推广", Estimate = (l.Estimate * (agentType == 1 ? GetRate(l.Rate_i) : GetRate(l.Rate_ii))).ToString("C"), Income = (l.Income * (agentType == 1 ? GetRate(l.Rate_i) : GetRate(l.Rate_ii))).ToString("C"), UserName = l.UserName };
            res.State = true;
            res.Message = "请求成功";
            res.Datas = newList;


            return Json(res);
        }
        /// <summary>
        /// 获取当前代理获取佣金
        /// </summary>
        /// <param name="commission"></param>
        /// <returns></returns>
        public decimal GetRate(int commission)
        {
            return (decimal)(((100 - SysConfig.rate_all) * (commission / 100.00)) / 100.00);


        }


        /// <summary>
        /// 合伙人推广统计
        /// </summary>
        public ActionResult HhrTGTJ()
        {
            return View();
        }
        public ActionResult GetHhrTGTJ(int dateType = 1)
        {
            Result res = new Result() { State = false, Message = "请求失败" };

            // int pi = 1;
            int ps = 7;
            int count = 0;
            ProductEffectDAL dal = new ProductEffectDAL();
            string where = " and 1=1 ";

            if (dateType > 0)
            {
                switch (dateType)
                {
                    case 1:
                        where += string.Format(" and p.CreateDate>='{0}'", DateTime.Now.ToString("yyyy-MM-01"));
                        break;
                    case 2:
                        where += string.Format(" and p.CreateDate>='{0}' and p.CreateDate<'{1}'", DateTime.Now.AddMonths(-1).ToString("yyyy-MM-01"), DateTime.Now.ToString("yyyy-MM-01"));

                        break;
                    case 3:
                        break;


                    default:
                        break;
                }
            }
            string tableName = "ProductEffect_" + AgencyUsers.promoter_id;
            string sql = " select * from [" + tableName + "] p left join  [dbo].[AgencyUsers] au on p.username=au.username ";

            sql = "select 1 UserName, CreateDate,sum(clicknum) clicknum,sum(paynum)paynum,sum(estimate)estimate,sum(income)income from [" + tableName + "]   p left join  [dbo].[AgencyUsers] au on p.username=au.username  where  au.superior=@auid " + where + "  group by createdate  ";
            sql += " union all ";
            sql += " select 2 UserName, CreateDate,sum(clicknum) clicknum,sum(paynum)paynum,sum(estimate)estimate,sum(income)income from [" + tableName + "]   p left join  [dbo].[AgencyUsers] au on p.username=au.username  where  ";
            sql += "  au.onthe_superior=@auid " + where + " group by createdate  ";



            var list = dal.List<ProductEffect>(sql, new { auid = AgencyUsers.id }).ToList();

            //var list = dal.ListPage(where, " createdate desc ", ps, 1, out count, new { promoter_id = AgencyUsers.promoter_id });

            List<string> dateTimeArray = new List<string>();
            //下级代理
            List<string> djtjArray = new List<string>();
            List<string> ddtjArray = new List<string>();
            List<string> ygtjArray = new List<string>();
            List<string> jstjArray = new List<string>();
            //下下级代理
            List<string> djtjArray2 = new List<string>();
            List<string> ddtjArray2 = new List<string>();
            List<string> ygtjArray2 = new List<string>();
            List<string> jstjArray2 = new List<string>();


            //开始时间

            for (int i = 1; i < DateTime.Now.Day; i++)
            {
                dateTimeArray.Add(string.Format("{0}-{1}", DateTime.Now.Month, i));
                var m = list.FindAll(l => ((l.CreateDate.Month == DateTime.Now.Month) && (l.CreateDate.Day == i)));
                if (m != null && m.Count > 0)
                {
                    var model = m.Find(l => (l.UserName == "1"));
                    if (model != null)
                    {
                        djtjArray.Add(model.ClickNum.ToString());
                        ddtjArray.Add(model.PayNum.ToString());
                        ygtjArray.Add(string.Format("{0:N}", (model.Estimate * GetRate(model.Rate_i))));
                        jstjArray.Add(string.Format("{0:N}", model.Income * GetRate(model.Rate_i)));
                    }
                    else
                    {
                        djtjArray.Add("0");
                        ddtjArray.Add("0");
                        ygtjArray.Add("0.00");
                        jstjArray.Add("0.00");

                    }
                    var model2 = m.Find(l => (l.UserName == "2"));
                    if (model2 != null)
                    {
                        djtjArray2.Add(model2.ClickNum.ToString());
                        ddtjArray2.Add(model2.PayNum.ToString());
                        ygtjArray2.Add(string.Format("{0:N}", model2.Estimate * GetRate(model2.Rate_i)));
                        jstjArray2.Add(string.Format("{0:N}", model2.Income * GetRate(model2.Rate_i)));
                    }
                    else
                    {
                        djtjArray2.Add("0");
                        ddtjArray2.Add("0");
                        ygtjArray2.Add("0.00");
                        jstjArray2.Add("0.00");
                    }

                }
                else
                {
                    djtjArray.Add("0");
                    ddtjArray.Add("0");
                    ygtjArray.Add("0.00");
                    jstjArray.Add("0.00");
                    djtjArray2.Add("0");
                    ddtjArray2.Add("0");
                    ygtjArray2.Add("0.00");
                    jstjArray2.Add("0.00");
                }





            }

            //list.ForEach(l =>
            //{
            //    dateTimeArray.Add(l.CreateDate.ToString("MM-dd"));
            //    djtjArray.Add(l.ClickNum.ToString());
            //    ddtjArray.Add(l.PayNum.ToString());
            //    ygtjArray.Add(string.Format("{0:N}", l.Estimate));
            //    jstjArray.Add(string.Format("{0:N}", l.Income));

            //});


            res.State = true;
            res.Message = "请求成功";
            res.Datas = new { dateTime = dateTimeArray.ToArray(), djtj = djtjArray.ToArray(), ddtj = ddtjArray.ToArray(), ygtj = ygtjArray.ToArray(), jstj = jstjArray.ToArray(), djtj2 = djtjArray2.ToArray(), ddtj2 = ddtjArray2.ToArray(), ygtj2 = ygtjArray2.ToArray(), jstj2 = jstjArray2.ToArray() };
            return Json(res);
        }


        /// <summary>
        /// 转发到群
        /// </summary>
        /// <param name="auctionId"></param>
        /// <returns></returns>
        public JsonResult ApplyZhuanfa(string auctionId)
        {


            var res = new RobotApiHelper().FrontItemSends(AgencyUsers.promoter_id.ToString(), AgencyUsers.username, auctionId);


            return Json(new Result() { State = true, Message = "转发成功" });

        }



        /// <summary>
        /// 我要发单
        /// </summary>
        /// <returns></returns>
        public ActionResult WYFD()
        {
            ViewBag.state = "-1";
            var list = new AgencyRobotDAL().GetListByAu_id(UserSession.user_id);

            if (list != null && list.Count >= 0)
            {
                var model = list.FirstOrDefault();
                var times = model.SendTimeStr.Split(',');
                ViewBag.time1 = times[0].Split('-')[0];
                ViewBag.time2 = times[0].Split('-')[1];
                ViewBag.time3 = times[1].Split('-')[0];
                ViewBag.time4 = times[1].Split('-')[1];
                ViewBag.time5 = times[2].Split('-')[0];
                ViewBag.time6 = times[2].Split('-')[1];

                ViewBag.FlockSendSecond = model.FlockSendSecond;

            }
            else
            {
                ViewBag.time1 = "08:00";
                ViewBag.time2 = "22:00";
                ViewBag.time3 = "00:00";
                ViewBag.time4 = "00:00";
                ViewBag.time5 = "00:00";
                ViewBag.time6 = "00:00";

            }
            var key = RedisKey.AgentIndependentSendType(AgencyUsers.promoter_id.ToString(), AgencyUsers.id.ToString());
            string state = RedisHelper.Single_Get_Itme<string>(key);
            if (!string.IsNullOrEmpty(state))
            {
                ViewBag.state = state;
                
            }
            

            return View(list);
        }


        [HttpPost]
        public JsonResult PostWYFD(WYFDDTO model)
        {
            Result res = new Result() { State = true, Message = "提交成功" };

            if ((model.time1 > model.time2) || (model.time3 > model.time4) || (model.time5 > model.time6))
            {
                res.State = false;
                res.Message = "结束时间不能大于开始时间";
                return Json(res);
            }
            
            string SendTimeStr = string.Format("{0}-{1},{2}-{3},{4}-{5}", model.time1.ToString("HH:mm"), model.time2.ToString("HH:mm"), model.time3.ToString("HH:mm"), model.time4.ToString("HH:mm"), model.time5.ToString("HH:mm"), model.time6.ToString("HH:mm"));
            var r = new AgencyRobotDAL().UpdateFlockInfo(model.FlockSendSecond, SendTimeStr, UserSession.user_id);
            if (r)
            {
                var key = RedisKey.AgentIndependentSendType(AgencyUsers.promoter_id.ToString(), UserSession.user_id.ToString());

                var type = RedisHelper.Single_Get_Itme<string>(key);

                if (string.IsNullOrEmpty(type))
                {
                    RedisHelper.Single_Remove_Itme(key);
                    RedisHelper.Single_Set_Itme<string>(key, "-1");
                }




            }
            //更新机器人api 接口
            foreach (var item in model.flockNames.Split(','))
            {
                if (!string.IsNullOrEmpty(item))
                {
                    new RobotApiHelper().UpdateAgentConfig(AgencyUsers.promoter_id.ToString(), AgencyUsers.username, item);
                }

            }


            return Json(res);
        }

        [HttpPost]
        public JsonResult GetWXLoginImg(string flockNames, bool IsRefresh=false)
        {
            Result res = new Result();
            var key = RedisKey.AgentIndependentSendType(AgencyUsers.promoter_id.ToString(), AgencyUsers.id.ToString());
            string state = RedisHelper.Single_Get_Itme<string>(key);
            if (IsRefresh||string.IsNullOrEmpty(state))
            {
                    RedisHelper.Single_Remove_Itme(key);
                    RedisHelper.Single_Set_Itme<string>(key, "-1");
                    state = RedisHelper.Single_Get_Itme<string>(key);
            }
            
            //-1没有登录或掉线0等待扫码1正在扫码2扫码失败3加载数据4正在发单
            
            
            if (IsRefresh||state == "-1" || state == "2")
            {
                //请求机器人
                new RobotApiHelper().AddAgentWxSendRobot(AgencyUsers.promoter_id.ToString(), AgencyUsers.username, AgencyUsers.id.ToString(), flockNames);
            }
            var value = "";
            var datas = "";

            switch (state)
            {
                case "-1":
                case "0":
               
                    string imgUrl = ConfigurationManager.AppSettings["agentWXLoginImg"]; ;
                    string imgPath = string.Format("{0}/{1}_{2}.png", imgUrl, AgencyUsers.promoter_id, AgencyUsers.id);
                    res.Datas = imgPath;
                    res.Message = "成功";
                    break;
                case "1":
                    res.Datas = "1";
                    res.Message = "正在扫码";
                    break;
                case "2":
                      res.Datas = "2";
                    res.Message = "扫码失败";

                    break;
                case "3":
                    res.Datas = "3";
                    res.Message = "加载数据";
                    break;
                case "4":
                    res.Datas = "4";
                    res.Message = "已经登陆";
                    break;
                default:
                    break;
            }
            res.State = true;
            return Json(res);
        }

       //商品转链
        public ActionResult ConventLink()
        {
            return View();
        }

    }

    public class WYFDDTO
    {
        public int au_id { get; set; }
        public string flockNames { get; set; }

        public string flockIds { get; set; }

        public DateTime time1 { get; set; }
        public DateTime time2 { get; set; }
        public DateTime time3 { get; set; }
        public DateTime time4 { get; set; }
        public DateTime time5 { get; set; }
        public DateTime time6 { get; set; }
        public int FlockSendSecond
        {
            get;
            set;

        }

        /// <summary>
        ///1没有登录或掉线0等待扫码1正在扫码2扫码失败3加载数据4正在发单 
        /// </summary>
        public int type { get; set; }

    }
}